import React, { useRef } from 'react';
import { message, Button, Space } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormDatePicker,
  ProFormSwitch,
  ProFormDigitRange,
} from '@ant-design/pro-form';
import { add, update } from '../service';
const Form = (props) => {
  console.log();

  // 新增
  const handleAdd = async (values) => {
    try {
      var re = await add(values);
      if (re.isSuccess) {
        message.success(re.msg);
      } else {
        message.error(re.msg);
      }
      return re.isSuccess;
    } catch (error) {
      message.error('操作异常');
      return false;
    }
  };

  // 修改
  const handleUpdate = async (values) => {
    try {
      var re = await update(values);
      if (re.isSuccess) {
        message.success(re.msg);
      } else {
        message.error(re.msg);
      }
      return re.isSuccess;
    } catch (error) {
      message.error('操作异常');
      return false;
    }
  };

  return (
    <ModalForm
      submitter={props.state != 'read'}
      labelCol={{ span: 4 }}
      title="角色"
      layout="horizontal"
      formRef={props.formRef}
      visible={props.modalVisit}
      onVisibleChange={props.setModalVisit}
      initialValues={{
        state: true,
      }}
      onFinish={async (values) => {
        values.state = Number(values.state);
        var data = false;
        if (props.formRef?.current?.getFieldValue('id')) {
          data = await handleUpdate(values);
        } else {
          data = await handleAdd(values);
        }
        if (data) {
          props.actionRef.current.reload();
        }
        return data;
      }}
    >
      <ProFormDigitRange mode={props.state} name="id" hidden={true} />
      <ProFormText
        mode={props.state}
        name="name"
        label="角色名称"
        placeholder="请输入名称"
        rules={[
          { required: true, message: '不能为空' },
          { type: 'string', max: 20 },
        ]}
      />
    </ModalForm>
  );
};
export default Form;
